//
//  BaseTabbarController.swift
//  DYSwiftFramework
//
//  Created by huangdeyu on 2021/10/20.
//  Copyright © 2021 none. All rights reserved.
//

import Foundation
import UIKit
import SnapKit

class BaseTabbarController: UIViewController ,RouterControllerMixin{
    private var tabbarView:DDTabbarView?
    private var controllers:[UIViewController]?
    var selectedIndex = 0
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        controllers = [HomeViewController(),FoundMainViewController()]
        addTabbar()
        changeToViewController(index: 0)
    }
    
    private func addTabbar() {
        let home = DDTabbarItem(title: "首页", titleColor: Color.init(hex: 0xa4b8be)!, titleSelectedColor: Color.init(hex: 0xd55548)!, image: UIImage.init(named: "home")!, selectedImage: UIImage.init(named: "home_selected")!)
        let live = DDTabbarItem(title: "直播", titleColor: Color.init(hex: 0xa4b8be)!, titleSelectedColor: Color.init(hex: 0xd55548)!, image: UIImage.init(named: "live")!, selectedImage: UIImage.init(named: "live_selected")!)
        tabbarView = DDTabbarView(items: [home,live], selectedIndex: selectedIndex)
        tabbarView?.didSelctedIndex = {[weak self] (index) in
            self?.changeToViewController(index: index)
        }
        view.addSubview(tabbarView!)
        tabbarView?.snp.makeConstraints({ (make) in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(TABBAR_HEIGHT)
        })
    }
    
    private func changeToViewController(index:Int) {
        let lastVC = controllers?[selectedIndex]
        if let vc = lastVC, let _ = vc.parent{
//            vc.willMove(toParentViewController: nil)
            vc.view.removeFromSuperview()
//            vc.removeFromParentViewController()
        }
        selectedIndex = index
        let controller = controllers?[index]
        if let ctrol = controller {
            if !self.childViewControllers.contains(ctrol) {
                self.addChildViewController(ctrol)
            }
            self.view.addSubview(ctrol.view)
            ctrol.view.snp.makeConstraints { (make) in
                make.left.top.right.equalToSuperview()
                make.bottom.equalToSuperview().inset(TABBAR_HEIGHT)
            }
        }
        tabbarView?.setSelectedIndex(index: selectedIndex)
    }
    
    func changeToIndex(index:Int) {
        if selectedIndex == index {
            return
        }
        selectedIndex = index
        tabbarView?.didSelctedIndex!(index)
    }
    
}

